package com.dun.re.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.dun.re.service.LoginService;
import com.dun.re.vo.User;

@Controller
@RequestMapping(value = "/loginController")
@SessionAttributes({"user"})
public class LoginController {

	@Autowired
	private LoginService loginService;

	/**
	 * ModelAttribute provides the User Object for new request attribute
	 * 
	 * @return
	 */
	@ModelAttribute
	public User newRequest() {
		return new User();
	}

	/**
	 * loads the login page
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	/**
	 * Method is for validating the user and if no errors home page is loaded
	 * 
	 * @param user
	 * @param result
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
	public String userLogin(@Valid User user, BindingResult result, Model model) {
		String returnView;
		
		returnView = "login";
		if (result.hasErrors()) {

			return returnView;
		}
		try {
			List<User> users = loginService.getUsers();
			if (users.size() > 0) {
				for (User dbUser : users) {
					if ((user.getUserName().equalsIgnoreCase(dbUser
							.getUserName()))
							&& (user.getPassword().equalsIgnoreCase(dbUser
									.getPassword()))) {
						model.addAttribute("user", user);
						returnView = "home";
						break;
					} else {
						model.addAttribute("loginError",
								"User does not exist in the database..");
						returnView = "login";
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return returnView;

	}
}
